<template>
  <div>
    <h4>发表评论</h4>
    <hr />
    <textarea placeholder="最多吐槽120个字" maxlength="120" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postMsg">发表评论</mt-button>

    <!-- 评论区列表 -->
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item,index) in cmtList" :key="index">
        <div class="cmt-item-title">第{{index+1}}楼&nbsp;用户:匿名用户&nbsp;发表时间：{{item.add_time}}</div>
        <div class="cmt-item-body">{{item.content}}</div>
      </div>
    </div>
    <mt-button type="danger" size="large" @click="loadMore">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from "mint-ui";
export default {
  data: function() {
    return {
      page: 1,
      cmtList: [],
      msg: ""
    };
  },
  created() {
    this.getComments();
  },
  methods: {
    //根据页数获取评论的数据
    async getComments() {
      const { data } = await this.$http.get(
        "/api/getcomments/" + this.newsId + "?pageindex=" + this.page
      );
      // console.log(data);
      if (data.message.length > 0) {
        this.cmtList = this.cmtList.concat(data.message);
      }
    },
    async postMsg() {
      //如果用户没有填写内容，则阻止其发表评论
      if (this.msg.trim().length <= 0) return Toast("请填写评论内容");
      const { data } = await this.$http.post(
        "/api/postcomment/" + this.newsId,
        { content: this.msg.trim() }
      );
      // console.log(data);
      if (data.status === 0) {
        this.cmtList.unshift({
          user_name: "匿名用户",
          add_time: new Date(),
          content: this.msg.trim()
        });
        this.msg = "";
      }
    },
    loadMore() {
      this.page++;
      this.getComments();
    }
  },

  props: ["newsId"] //接收父组件传递过来的新闻id
};
</script>

<style lang="scss" scoped>
textarea {
  font-size: 13px;
}
.cmt-list {
  .cmt-item {
    line-height: 30px;
    .cmt-item-title {
      font-size: 14px;
      background-color: #ddd;
    }
    .cmt-item-body {
      font-size: 13px;
      text-indent: 2em;
    }
  }
}
</style>